#!/bin/bash
#Author: YangYi
#Date: 2023-12-06
#Version: v1

#Author: YangYi
#Date: 2024-01-02
#Version: v2
#AddMonitorAlter


#临时文件路径
SAVE_PATH=/app/paasadmin/CurrentMonitorAlarm.text

#告警伐值
ALERT_VALUE="100"

#格式化时间
TIME=`date +%F-%H:%M:%S`

#设置要保存的文件个数
SAVE_COUNT="48"

#文件过滤路径
FILTER_FILE=/app/paasadmin/CurrentMonitorAlarm/
sudo /bin/mkdir -p  $FILTER_FILE && chown -R paasadmin:paasadmin $FILTER_FILE

#存储路径
FILE_PATH=$FILTER_FILE$TIME-pid.txt

#监控采集文件
ALTER_FILE="/tmp/CurrentAlter.text"

#节点pid统计
NODEPIDSALL=`cd /sys/fs/cgroup/pids/kubepods && find -iname "pids.*" | awk -F "/" '{if ($4=="pids.current")print }' | xargs -I file sh -c 'echo -e file" \c" && cat file'|awk '$2 > 1' | awk '{print $2"/"$1}' | awk -F "/" '{print $1$4}' | awk -F "pod" '{print $1" "$2}' | sort -nr  > $SAVE_PATH`

#阈值告警
function AlertService(){
  cat $SAVE_PATH | while read results
    do
      result=`echo $results | awk '{print $2}'`
      #docker ps  | grep $result | grep -v "filebeat\|pause" | awk '{print $NF}' | awk -F "_" '{printf "{服务名:"$3"  所属空间:"$4"}"}' >> $FILE_PATH && cat $SAVE_PATH | grep $result | awk '{printf " current阈值:"$1}' >> $FILE_PATH && echo -e "\r" >> $FILE_PATH 
      docker ps  | grep $result | grep -v "filebeat\|pause" | awk '{print $NF}' | awk -F "_" '{printf $3","$4}' >> $FILE_PATH  && cat $SAVE_PATH | grep $result | awk '{printf ","$1}' >> $FILE_PATH  && echo -e "\r" >> $FILE_PATH
    done
  AlterFile=`ls -l | awk '{print $9}' | tail -1`

  awk -F "," '{if ($NF > 500){print $1",namespaces:"$2",value:"$3"level:warning,pods:"}}' $AlterFile 
  #awk -F "," '{if ($NF > 500) print}' $AlterFile | awk -F ":" '{print $2}' >> $ALTER_FILE && echo ",warning" >> $ALTER_FILE
}


#文件清理
function File_Cleanup(){
cd $FILTER_FILE
#1 判断文件个数
count=$(ls -l | wc -l)
delcount=$[$count - $SAVE_COUNT]
#2 是否进行删除
if [ $delcount -gt 0 ] ; then
        #获取时间最久的文件夹名称
        filesname=$(ls -tr | head -n $delcount)
        filesname=${filesname// /}
        filesarr=($filesname)
        #循环依次删除时间久的文件
        for each in ${filesarr[*]}
          do
          sudo rm -rf $each
          done
fi
}

File_Cleanup
AlertService

